package com.sun.wanandroid.ui.splash

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import com.sun.module_base.app.BaseViewModel
import com.sun.module_network.utils.logd
import dagger.hilt.android.lifecycle.HiltViewModel
import java.util.ServiceLoader
import javax.inject.Inject

/**
 *@author:sunc
 *@time :2025/7/25 8:58
 *@desc: 描述
 */
@HiltViewModel
class SplashViewModel @Inject constructor() : BaseViewModel() {
    val mCurrentTaskIndex = mutableIntStateOf(0)

    private var openDialog = mutableStateOf(true)

    private val composableMap = HashMap<Int, ISplashComposableTask>()

    init {
//        MyServiceLoader.load<ISplashComposableTask>().
        ServiceLoader.load<ISplashComposableTask>(ISplashComposableTask::class.java).forEach {
            //检查index 是否为null ，null 抛异常
//            check(composableMap[it.index] != null) { "ISplashComposableTask index is null" }
            if (composableMap[it.index] != null) {
                throw DuplicateIndexException(composableMap[it.index]!!)
            }

            composableMap[it.index] = it

        }
    }

    private fun getComposable(index: Int): ISplashComposableTask? = composableMap[index]


    @Composable
    fun ExecuteCurrent() {
        val composableTask = getComposable(mCurrentTaskIndex.intValue)

//        check(composableTask != null) { "composableTask: $composableTask is null" }
        composableTask?.SplashComposableItem()
    }

    @Composable
    fun FindNextTask() {
        LaunchedEffect(key1 = mCurrentTaskIndex.intValue, block = {
            "find next available task ${mCurrentTaskIndex.intValue}".logd()
            for (i in (mCurrentTaskIndex.intValue + 1)..100) {
                "Try task index $i".logd()
                if (getComposable(i) != null) {

                    "Got next available task $i ${getComposable(i)} is available".logd()
                    mCurrentTaskIndex.intValue = i
                    break
                }
            }
        })
    }
}